<?php

namespace App\Http\Controllers\Api\v1;

use App\Models\Answer;
use App\Models\Api\User; //测试
use App\Models\Capital;
use App\Models\Divination;
use App\Models\Orders;
use App\Models\Question;
use App\Models\Stage;
use App\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class QuestionController extends BaseController
{

    public function __construct()
    {
        parent::__construct(); // 接口调用验证
    }
    public static function rule($type, $money, $count)
    {
        if ($type != 1 && $type != 4 && $type != 5) {
            $array = [
                3  => [2.1],
                5  => [2.1, 1.4],
                8  => [2.1, 2.1, 1.4],
                10 => [2.1, 2.1, 1.4, 1.4],
                12 => [2.1, 2.1, 1.4, 1.4, 1.4],
                20 => [2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 1.4],
            ];
        } else {
            $array = [
                5  => [3.5],
                8  => [3.5, 2.1],
                12 => [3.5, 2.8, 2.1],
                16 => [3.5, 3.5, 2.1, 2.1],
                20 => [3.5, 3.5, 2.8, 2.1, 2.1],
                30 => [3.5, 3.5, 3.5, 2.8, 2.1, 2.1, 2.1],
            ];
        }

        if (!isset($array[$money][$count])) {
            return false;
        } else {
            return $array[$money][$count];
        }

    }
    /**
     * $param header参数忽略
     * @param type 0全部拉取，1星盘，2骰子，3塔罗牌，4合盘，5八字
     * @param order
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 问答列表
     *
     */
    public function questions(Request $request)
    {

        $data  = [];
        $type  = $request->input('type', 1);
        $page  = $request->input('page', 1);
        $order = $request->input('order', 'pv');

        $data = Question::select(["*"])
            ->with(['user' => function ($query) {
                $query->select(['id', 'nickname', 'avatar']);
            }])
            ->where('state', 1)
            ->where('parent_id', 0)
            ->where('type', $type)
            ->orderBy($order, 'desc')
            ->paginate(10, ['page' => $page]);
        $new_time = strtotime(date("y-m-d H:i:s"));
        foreach ($data as $question) {

            $time = floor($new_time - strtotime($question->created_at));

            if ($time <= 60) {
                $question->time = '刚刚';
            } elseif ($time <= 120 && $time > 60) {
                $question->time = '1分钟前';
            } elseif ($time <= 180 && $time > 120) {
                $question->time = '2分钟前';
            } elseif ($time <= 1800 && $time > 180) {
                $question->time = '半小时前';
            } elseif ($time <= 3600 && $time > 1800) {
                $question->time = '一小时前';
            } elseif ($time <= 7200 && $time > 3600) {
                $question->time = '两小时前';
            } else {
                $question->time = $question->created_at;
            }
        }
        return show(200, '问答列表', $data);
    }
    /**
     * $param header参数忽略
     * @param type 0全部拉取，1星盘，2骰子，3塔罗牌，4合盘，5八字
     * @param order
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 问答详情
     *
     */
    public function detail(Request $request)
    {

        $id   = $request->input('id', 0);
        $info = Question::select("*")->where('id', $id)->first();
        if ($info->state == 0) {
            return show(config('code.error'), '失效链接');
        }

        $info->update(['pv' => $info->pv + 1]);

        $answers = Answer::with(['user' => function ($user) {
            $user->select(['id', 'nickname', 'avatar']);
        }, 'questions' => function ($q) {
            $q->where('state', '!=', 0);
        }])->where('question_id', $info->id)->get();

        foreach ($answers as $k => $answer) {
            foreach ($answer['questions'] as $v => $ques) {
                $answers[$k]['questions'][$v]['subanswer'] = Answer::with('user')->where('question_id', $ques['id'])->get();
            }
            if ($answer['user_id'] != $request->uid) {
                if ($request->uid != $info->user_id) {
                    $answer['content'] = '此条答案仅题主和答主可见';
                }
            }

        }

        $divination = Divination::where(['id'=>$info->divination_id]);
        $message    = [];

        $user = User::find($request->uid);

        switch ($info->type) {
            case 1:
                if ($user->chart_state == 0) {
                    $message = '请先进行星盘答题认证，通过即可参与答题！';
                }

                break;
            case 2:
                if ($user->dice_state == 0) {
                    $message = '请先进行骰子答题认证，通过即可参与答题！';
                }

                $divination = $divination->with(['plant', 'constellation', 'palace']);
                break;
            case 3:
                if ($user->tarot_state == 0) {
                    $message = '请先进行塔罗答题认证，通过即可参与答题！';
                }

                $divination = $divination->with(['before', 'now', 'future']);
                break;
            case 4:
                if ($user->chart_state == 0) {
                    $message = '请先进行星盘答题认证，通过即可参与答题！';
                }

                break;
            case 5:
                if ($user->egiht_state == 0) {
                    $message = '请先进行星盘答题认证，通过即可参与答题！';
                }

                break;
        }
        $divination= $divination->first(['id', 'type_id', 'user_id', 'problem', 'planet_id', 'constellation_id', 'palace_id', 'before_id', 'now_id', 'future_id']);

        if (empty($divination)) {
            return show(200, '成功', $data);
        }

        $a_num = Answer::where('user_id', $request->uid)->where('parent_question_id', $id)->get()->count();
        //有过答案
        if ($a_num >= 1) {
            //主问题下的所有追问
            $all_quesitons = Question::where('parent_question_id', $id)->get();
            $q_num         = 1;
            foreach ($all_quesitons as $que) {
                if (Answer::find($que->parent_id)->user_id == $request->uid) {
                    $q_num += 1;
                }
            }
            if ($a_num < $q_num) {
                //'can'有资格答题
                $submit = 'can answer';
            } else {
                $submit = 'cannot answer';
            }
        } else {
            //第一次进来的回答者
            $submit = 'first_answer';
        }
        //题主身份判断
        if ($request->uid == $info->user_id) {
            $submit = '你是提问者不能答题';
        }

        $data = [
            'info'       => $info,
            'answers'    => $answers,
            'divination' => $divination,
            'message'    => $message,
            'submit'     => $submit,
        ];

        return show(200, '加载成功', $data);
    }
    /**
     * $param header参数忽略
     * @param type 0全部拉取，1星盘，2骰子，3塔罗牌，4合盘，5八字
     * @param order
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 问答添加
     *
     */
    public function add(Request $request)
    {
        $data      = [];
        $stage_id  = $request->input('stage_id', 0);
        $divi_id   = $request->input('divi_id', 0);
        $questions = $request->input('question', 0);
        $pay_type  = $request->input('pay_type');
        $userid    = $request->input('uid');
        $divi      = Divination::where('id', $divi_id)->first();
        $user      = User::find($userid);
        if ($pay_type == 1) {
            $ticket = $user->ticket;
            if ($ticket <= 0) {
                return $this->error(-1, '提问券数量不足!');
            }

            $question = Question::create([
                'user_id'       => $userid,
                'type'          => $divi->type_id,
                'question'      => $questions,
                'divination_id' => $divi_id,
                'money'         => 0,
                'answerer_num'  => 1,
                'balance'       => 0,
                'pay_type'      => 1,
                'state'         => 1,
            ]);
            $user->update(['ticket' => $user->ticket - 1]);

            //提问券随机匹配功能
            $users = User::where('forbidden', 0);
            switch ($divi->type_id) {
                case 1: //星盘
                    $users = $users->where('chart_state', 1)->get()->toArray();
                    break;
                case 2: //骰子
                    $users = $users->where('dice_state', 1)->get()->toArray();
                    break;
                case 3: //塔罗
                    $users = $users->where('tarot_state', 1)->get()->toArray();
                    break;
                case 4: //星盘
                    $users = $users->where('tarot_state', 1)->get()->toArray();
                    break;
                case 5: //八字
                    $users = $users->where('egiht_state', 1)->get()->toArray();
                    break;
            }
            shuffle($users);
            $users            = array_slice($users, 0, 2);
            $data['name']     = $user->name;
            $data['question'] = $question->question;
            foreach ($users as $user) {
                Ticket::create(['question_id' => $question->id, 'user_id' => $user['id']]);
                $data['openid'] = $user['openid'];
                Push::Question_push($data);
            }
            return response()->json([
                'code'        => 0,
                'type'        => 1,
                'question_id' => $question->id,
            ]);
        }

        $order_id = rand(100000000, 999999999);
        $stage    = Stage::where('id', $request->stage_id)->first();

        $question = Question::create([
            'user_id'       => $userid,
            'type'          => $divi->type_id,
            'question'      => $request->question,
            'divination_id' => $divi->id,
            'money'         => $stage->money,
            'answerer_num'  => $stage->answers,
            'balance'       => $stage->money,
            'pay_type'      => 2,
        ]);
        Orders::create(['user_id' => $userid, 'status' => 0, 'price' => $stage->money, 'order_id' => $order_id, 'question_id' => $question->id, 'stage_id' => $stage->id]);

        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 追问
     */
    public function chase_ask(Request $request)
    {
        $id        = $request->get('question_id');
        $content   = $request->get('question');
        $answer_id = $request->get('answer_id');
        if (empty($content)) {
            return show(config('code.error'), '请填写追问信息哟~');
        }
        $question       = Question::where(['id' => $id])->first();
        $question_count = Question::where('parent_question_id', $id)->count();
        $answer_count   = Answer::where('parent_question_id', $id)->count();
        if ($question_count + 1 < $answer_count) {
            return show(config('code.error'), '请等待答主先回答上个追问哟~');
        }
        $divi = Divination::where('id', $question->divination_id)->first();

        if ($divi->type_id != 1 || $divi->type_id != 4) {
            $money    = 3;
            $stage_id = 7;
        } else {
            $money    = 5;
            $stage_id = 1;
        }
        $data['question'] = $question->question;
        $question         = Question::create([
            'user_id'            => $request->uid,
            'type'               => $question->type,
            'pay_type'           => 2,
            'question'           => $content,
            'divination_id'      => $question->divination_id,
            'money'              => $money,
            'answerer_num'       => 1,
            'balance'            => $money,
            'parent_id'          => $answer_id,
            'parent_question_id' => $id,
        ]);

        //创建问题成功

        $answer         = Answer::find($answer_id);
        $data['reask']  = $question->question;
        $data['answer'] = $answer->content;
        if ($answer->type == 2) {
            $data['answer'] = '语音';
        }
        $data['open_id'] = User::find($answer->user_id)->openid;

        $data['question_id'] = $id;

        $order_id = rand(100000000, 999999999);

        Orders::create(['user_id' => $request->uid, 'status' => 0, 'price' => $money, 'order_id' => $order_id, 'question_id' => $question->id, 'stage_id' => $stage_id]);

        return $this->pay($money, $question, $order_id, 2);

    }

    //type 1:文字 2：语音
    public function publish_comment(Request $request)
    {
        $content = $request->get('content');
        $id      = $request->get('question_id');
        $type    = $request->get('type');
        $time    = $request->get('time');
        $num     = strlen($content);
        $user    = User::find($request->uid);
        if ($user->forbidden == 1) {
            return show(config('code.error'), '您已经被禁言了！');
        }

        if ($user->answers <= 0) {
            return show(config('code.error'), '答题次数没了哟~！');
        }

        if (empty($num)) {
            return show(config('code.error'), '问题内容为空');
        }

        $question = Question::where(['id' => $id])->first();
        if (!$question) {
            return show(config('code.error'), '数据不存在');
        }
//
        //        if($question->user_id == $request->uid){
        //            return '<script>alert("不能回答自己的问题哟 ~！");history.go(-1);</script>';
        //        }

        $question_id = Answer::where(['question_id' => $id]);
        $url         = 'questionDetail?id=' . $id;

        try {
            $ques_id     = $question_id->where(['user_id' => $request->uid])->first();
            $is_chaseAsk = Question::where(['parent_id' => $ques_id->id, 'status' => 0, 'state' => 1])->first();
            if (!empty($ques_id)) {
                if (!empty($is_chaseAsk)) {
                    if ($request->uid != $ques_id->user_id) {
                        return show(config('code.error'), '您不能回答该问题哟~！');
                    }
                    if ($question->type != 1 && $question->type != 4) {
                        if ($type == 1) {
                            if ($num < 90) {
                                return show(config('code.error'), '文字回答不足30字，请重试！');
                            }
                        }
                        $money = 2.1;
                    } else {
                        if ($type == 1) {
                            if ($num < 360) {
                                return show(config('code.error'), '文字回答不足120字，请重试！');
                            }
                        }
                        $money = 3.5;
                    }
                    $answer = Answer::create([
                        'question_id'        => $is_chaseAsk->id,
                        'parent_question_id' => $is_chaseAsk->parent_question_id,
                        'user_id'            => $request->uid,
                        'money'              => $money,
                        'content'            => $content,
                        'time'               => $time,
                        'type'               => $type,
                    ]);
                    Question::where(['parent_id' => $ques_id->id])->update(['status' => 1]);
                    User::where(['id' => $request->uid])->update(['get_balance' => $user->get_balance + $money, 'answers' => $user->answers - 1]);
                    $chase_ask_user = User::find($is_chaseAsk->user_id);
                    //资金明细 type 1答题2退款3提现
                    $data            = [];
                    $data['user_id'] = $request->uid;
                    $data['type']    = '1';
                    $data['money']   = $money;
                    $data['num']     = date('YmdHis', time()) . rand(1000, 9999);
                    Capital::create($data);
                    $info                = [];
                    $info['openid']      = $chase_ask_user->openid;
                    $info['question']    = $is_chaseAsk->question;
                    $info['answer_name'] = $user->name;
                    $info['time']        = $answer->created_at->format('Y-m-d H:i:s');
                    $info['question_id'] = $id;
                    Push::push_new_answer($info);
                    return show(config('code.success'), '回答成功', $info);
                } else {
                    return show(config('code.error'), '您已经答过该题目~');
                }
            }
        } catch (\Exception $e) {
            if ($question->pay_type != 1) {
                if ($question->balance == 0) {
                    return show(config('code.error'), '该题已被关闭了哟！');
                }
            }

            if ($question->answerer_now >= $question->answerer_num) {
                return show(config('code.error'), '该题已到答题上限了哟！');
            }

            if ($question->type != 1 && $question->type != 4) {
                if ($type == 1) {
                    if ($num < 90) {
                        return show(config('code.error'), '文字回答不足30字，请重试！');
                    }
                }
                if ($question->type == 2) {
                    if ($user->dice_state != 1) {
                        return show(config('code.error'), '请先完成骰子答题认证哟~');
                    }
                }
                if ($question->type == 3) {
                    if ($user->tarot_state != 1) {
                        return show(config('code.error'), '请先完成塔罗答题认证哟~');
                    }
                }
            }
            if ($question->type == 1 || $question->type == 4) {
                if ($user->chart_state != 1) {
                    return show(config('code.error'), '请先完成星盘答题认证哟~');
                }
                if ($type == 1) {

                    if ($num < 360) {
                        return show(config('code.error'), '文字回答不足120字，请重试！');
                    }
                }
            }

            //回答答题券
            if ($question->money == 0 && $question->pay_type == 1) {
                if ($question->answerer_now >= 3) {
                    return show(config('code.error'), '该题已到答题上限了哟！');
                }

                Answer::create(['user_id' => $request->uid, 'money' => 0, 'question_id' => $id, 'content' => $content, 'time' => $time, 'type' => $type, 'rank' => $question_id->count() + 1]);
                Question::where(['id' => $id])->update(['answerer_now' => $question->answerer_now + 1]);
                User::where('id', $request->uid)->update(['answers' => $user->answers + 2]);
                return redirect($url);
            } else {
                $money = self::rule($question->type, $question->money, $question_id->count());
                if (!$money) {
                    return show(config('code.error'), '该题目已经答满~');
                }

                $app = app('wechat.official_account');

                $content = $content;

                if ($type == 2) {

                    $str = str_random(10);

                    $app->material->download($content, public_path('voice'), $str);

                    $filename = public_path('voice') . '/' . $str;

                    $command = "/usr/local/bin/ffmpeg -i $filename.amr $filename.mp3";

                    exec($command, $error);

                    exec("rm $filename.amr", $error);

                    $content = '/voice/' . $str . '.mp3';

                }

                $new_answer = Answer::create([
                    'user_id'            => $request->uid,
                    'money'              => $money,
                    'question_id'        => $id,
                    'parent_question_id' => $id,
                    'content'            => $content,
                    'time'               => $time,
                    'type'               => $type,
                    'rank'               => $question_id->count() + 1]);

                Question::where(['id' => $id])->update(['answerer_now' => $question->answerer_now + 1, 'balance' => $question->balance - ($money / 0.70)]);

                User::where('id', $request->uid)->update(['get_balance' => $user->get_balance + $money, 'answers' => $user->answers - 1]);

                //资金明细 type 1答题2退款3提现
                $data            = [];
                $data['user_id'] = $request->uid;
                $data['type']    = '1';
                $data['money']   = $money;
                $data['num']     = date('YmdHis', time()) . rand(1000, 9999);
                Capital::create($data);
                //推送
                $question_user            = User::find($question->user_id);
                $push_data['openid']      = $question_user->openid;
                $push_data['question']    = $question->question;
                $push_data['question_id'] = $question->id;
                $push_data['answer_name'] = $this->user->name;
                $push_data['time']        = $new_answer->created_at->format('Y-m-d H:i:s');
                Push::push_new_answer($push_data);

            }
            return show(config('code.success'), '答题成功');
        }
    }

    /**
     * [chase_answer 追加问答]
     * @AuthorHTL kingcode
     * @DateTime  2019-01-03
     * @param     Request    $request [content]
     * @return    [type]              [description]
     */
    public function chase_answer(Request $request)
    {
        $content = $request->get('content');
        $id      = $request->get('question_id');
        $type    = $request->get('type');
        $num     = strlen($content);
        $user    = User::where('id', $request->uid)->first();

        if ($user->account_state == 0) {
            return show(config('code.error'), '您已经被禁言了！');
        }
        if ($user->answers <= 0) {
            return show(config('code.error'), '答题次数没了哟');
        }
        if (empty($request->get('content'))) {
            return show(config('code.error'), '回答内容不能为空哟');
        }
        $question = Question::where('id', $id)->first();
        $answer   = Answer::where('id', $question->parent_id)->first();

        $question_id = Answer::where('question_id', $id);
        if ($request->uid != $answer->user_id) {
            return show(config('code.error'), '您不能回答该问题哟');
        }
        if ($question->type != 1) {
            if ($type == 1) {
                if ($num < 90) {
                    return show(config('code.error'), '文字回答不足30字，请重试！');
                }
            }
            if ($question_id->count() < 1) {
                $money = 2.1;
            } else {
                return show(config('code.error'), '该题已到答题上限了哟');
            }
        }
        if ($question->type == 1 || $question->type == 4) {
            if ($type == 1) {
                if ($num < 360) {
                    return show(config('code.error'), '文字回答不足120字，请重试！');
                }
            }
            if ($question_id->count() < 1) {
                $money = 3.5;
            } else {
                return show(config('code.error'), '该题已到答题上限了哟');
            }

        }

        $app = app('wechat.official_account');

        $content = $request->get('content');

        if ($type == 2) {

            $str = str_random(10);

            $app->material->download($content, public_path('voice'), $str);

            $filename = public_path('voice') . '/' . $str;

            $command = "/usr/local/bin/ffmpeg -i $filename.amr $filename.mp3";

            exec($command, $error);

            exec("rm $filename.amr", $error);

            $content = '/voice/' . $str . '.mp3';

        }

        Answer::create(['user_id' => $request->uid, 'money' => $money, 'question_id' => $id, 'content' => $content, 'type' => $type, 'rank' => $question_id->count() + 1]);
        $question->answerer_now = $question->answerer_now + 1;
        Question::where('id', $id)->update(['answerer_now' => $question->answerer_now]);

        User::where('id', $request->uid)->update(['get_balance' => $user->get_balance + $money, 'answers' => $user->answers - 1]);
        //资金明细 type 1答题2退款3提现
        $data            = [];
        $data['user_id'] = $request->uid;
        $data['type']    = '1';
        $data['money']   = $money;
        $data['num']     = date('YmdHis', time()) . rand(1000, 9999);
        Capital::create($data);
        return show(config('code.success'), '追答成功');
    }
}
